package com.alinesno.cloud.common.web.login.dialect.processor;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.spring5.context.SpringContextUtils;
import org.thymeleaf.templatemode.TemplateMode;

import com.alinesno.cloud.base.boot.entity.ManagerCodeEntity;
import com.alinesno.cloud.base.boot.service.IManagerCodeService;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;

/**
 * 字典标签(使用页面pageHandle标签)
 * @author WeiXiaoJin
 * @since 2019年1月31日 下午3:29:11
 */
@Deprecated
public final class DictionaryTagProcessor extends AbstractElementTagProcessor {
    
	private static final Logger log = LoggerFactory.getLogger(DictionaryTagProcessor.class) ; 

	private static final String TAG_NAME = "dict";
	private static final int PRECEDENCE = 1000;// 优先级

	public DictionaryTagProcessor(final String dialectPrefix) {
		super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE);
	}

	/**
	 * 标签内容解析
	 */
	@Override
	protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {

		ApplicationContext ctx = SpringContextUtils.getApplicationContext(context);
		
		final IModelFactory modelFactory = context.getModelFactory();
		final IModel model = modelFactory.createModel();
		IManagerCodeService managerCodeService = ctx.getBean(IManagerCodeService.class) ; 
		
		String type = tag.getAttributeValue("type"); // 类型
		String value = tag.getAttributeValue("value"); // 值(默认值) 
		String name = tag.getAttributeValue("name"); // 名称
		
		if(StringUtils.isBlank(value)) {
			value = "0" ;  // 默认为0(正常)
		}
		
		log.debug("type = {} , feigin = {}" , type , managerCodeService);
		
		StringBuffer sb = new StringBuffer() ; 
		if(StringUtils.isNotBlank(type)) {
			
			RestWrapper restWrapper = new RestWrapper() ; 
			restWrapper.eq("codeTypeValue", type)
					   .eq("hasStatus", "0") ; 
			List<ManagerCodeEntity> list = managerCodeService.findAll(restWrapper) ; 
			
			sb.append("<select class=\"form-control\" id=\""+name+"\" name=\""+name+"\">\n"); 
			
			for(ManagerCodeEntity m : list) {
				if(StringUtils.isNotBlank(value) && value.equals(m.getCodeValue())) {
					sb.append("<option value=\""+m.getCodeValue()+"\" selected>"+m.getCodeName()+"</option>\n") ; 
				} else {
					sb.append("<option value=\""+m.getCodeValue()+"\">"+m.getCodeName()+"</option>\n") ; 
				}
			}
			
			sb.append("</select>") ; 
		}
		
		model.add(modelFactory.createText(sb));
		structureHandler.replaceWith(model, false);
	}
}
